<?php
namespace app\listener;

use think\facade\Db;
use app\event\CodeUsed;
use app\admin\model\yxerp\code\Rule as RuleModel;
use app\admin\model\yxerp\code\Log as LogModel;

class CodeUsedListener
{
    public function handle(CodeUsed $event): void
    {
        $codeType = $event->codeType;
        $code     = $event->code;

        Db::startTrans();
        try {
            // 1. 查询日志是否存在
            $log = LogModel::where('code_type', $codeType)
                ->where('code', $code)
                ->lock(true)
                ->find();

            if ($log) {
                if ($log->status == 1) {
                    Db::rollback();
                    return;
                }
                $log->status = 1;
                $log->save();
            } else {
                LogModel::create([
                    'code_type'   => $codeType,
                    'code'        => $code,
                    'status'      => 1,
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            }

            // 2. 更新编号规则表
            if (preg_match('/(\d+)$/', $code, $matches)) {
                $num = intval($matches[1]);

                $rule = RuleModel::where('code_type', $codeType)
                    ->where('current_number', '<', $num)
                    ->find();

                if ($rule) {
                    $rule->current_number = $num;
                    $rule->save();
                }
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            trace('[CodeUsed事件] 异常：' . $e->getMessage(), 'error');
        }
    }
}
